$(function () {
    var courseStatus = $("#courseStatus").val();
    var courseType = $("#courseType").val();
    var params = {
        element: 'course-subject-box',
        context: 'course-subject-context',
        initSelect: true,
        removeBtn: true,
        initData: $("#subjectIds").val(),
        removeCallback: function (parentId, subjectIds) {
            resetSubjectIds()
        },
        confirmCallback: function (parentId, subjectIds) {
            resetSubjectIds()
        }
    };
        //初始化专业
        $.initSubject(params);
    /**
     * 重置专业ID串
     */
    function resetSubjectIds() {
        var _subjectIds = $.getAllSubjectIds("course-subject-context");
        $("input[name=subjectIds]").val(_subjectIds);
        $(".custom-select-teacher").html("");
        $('.custom-select-teacher').trigger('chosen:updated');
        initTeacherIds();
    }
    //课程类型
    var courseTypeKey = $("#courseType").val();

    //初始化时间控件
    initLayerDate("#validTime",true);
    initLayerDate("#limitDate", false);
    initLayerDate("#endTime", true);
    initLayerDate("#openTime", true);
    initLayerDate("#dontBuyTime", true);
    $(".course-info-desc-box").addClass('hide');
    $('.custom-select-teacher').chosen({ //选择教师的自定义框
        disable_search: true,
        display_selected_options: false
    });
    $('input[name="validType"]').on('ifChecked',function (event) {
        var validType = $(this).val();
        if (validType == 1) {//天数
            $("#day").removeClass("hide");
            $("#date").addClass("hide");
            $("input[name='validTime']").val('');
        } else if (validType == 2) {//时间段
            $("input[name='validDay']").val(0);
            $("#date").removeClass("hide");
            $("#day").addClass("hide");
        }
    })
    $("body").on('change',"select[name='validType']",function () {//改变课程期限类型
        var validType = $(this).val();
        if(validType==1){//天数
            $(".course-valid-day").removeClass("hide");
            $(".course-valid-time").addClass("hide");
            $("input[name='validDay']").val(0);
            $("input[name='validTime']").val('');
        }else if(validType==2){//时间段
            $("input[name='validDay']").val(0);
            $(".course-valid-time").removeClass("hide");
            $(".course-valid-day").addClass("hide");
        }
    }).on('change','select[name="memberCourse"]',function () {//会员课程
        var val = $(this).val();
        if(val==1){
            $(".or-price,.real-price").addClass("hide");
        }else{
            $(".or-price,.real-price").removeClass("hide");
        }
    }).on('ifChecked','input[name="_typeKey"]',function () {
        $("#courseType").val($(this).val());
        }).on('change','select[name="studyLimit"]',function () {// 学习限制
        var studyLimit = $(this).val();
        if(studyLimit==3){
            $(".score-percent-box").removeClass("hide");
        }else{
            $(".score-percent-box").addClass("hide");
        }
    }).on('blur',"input[name='validDay']",function () {//天数输入监听器
        var val  =$(this).val();
        if(!/^[0-9]+$/.test(val)){
            $(this).val(0);
        }
    }).on('blur',".course-price-in",function () {//课程价格输入监听
        var val = $(this).val();
        if(!/^[0-9]+(.[0-9]{1,2})?$/.test(val)){
            $(this).val(0);
        }
    }).on('blur',"input[name='scorePercent']",function () {// 得分率输入监听
        var val = $(this).val();
        if(!/^[0-9]+(.[0-9]{1,2})*$/.test(val)){
            $(this).val(0);
        }
    }).on('blur','.course-num-in',function () {//可视听人数,招生人数输入监听
        var val  =$(this).val();
        if(!/^[0-9]+$/.test(val)){
            $(this).val(0);
        }
    }).on("click","#selectTeacher",function () {//选择讲师
        $('.custom-select-teacher').blur();
        var subjectIds = $('input[name="subjectIds"]').val();
        if($.isEmptyObject(subjectIds)){
            icModale(0, '请先选择设置专业/科目');
            return;
        }
        selectTeacher('checkbox',subjectIds,'selectTeacherCallback','1');
    }).on('change', '.custom-select-teacher', function () { //选择教师时通过移除未选择的，使select看起来像input
        $('.custom-select-teacher option:not(:selected)').remove();
        $('.custom-select-teacher').trigger('chosen:updated');
        initTeacherIds();
    }).on('blur','input[name="validDay"]',function () {//过期天数
        var val  =$(this).val();
        if(!/^[0-9]+$/.test(val)){
            $(this).val(0);
        }
    }).on('focus','input[name="validDay"]',function () {//过期天数
        var _this = $(this);
        var val = _this.val();
        if(val==0){
            _this.val('');
        }
    }).on('focus','input[name="testNum"]',function () {//可视听人数
        var _this = $(this);
        var val = _this.val();
        if(val==0){
            _this.val('');
        }
    }).on('focus','input[name="initBuyNum"]',function () {//购买人数
        var _this = $(this);
        var val = _this.val();
        if(val==0){
            _this.val('');
        }
    }).on('blur','input[name="testNum"]',function () {//可视听人数
        var val  =$(this).val();
        if(!/^[0-9]+$/.test(val)){
            $(this).val(0);
        }
    }).on('blur','input[name="initBuyNum"]',function () {//购买人数
        var val  =$(this).val();
        if(!/^[0-9]+$/.test(val)){
            $(this).val(0);
        }
    }).on('focus','input[name="buyNum"]',function () {//招生人数
        var _this = $(this);
        var val = _this.val();
        if(val==0){
            _this.val('');
        }
    }).on('blur','input[name="buyNum"]',function () {//招生人数
        var val  =$(this).val();
        if(!/^[0-9]+$/.test(val)){
            $(this).val(0);
        }
    }).on('focus','input[name="orPrice"]',function () {//课程原价
        var _this = $(this);
        var val = _this.val();
        if(val==0){
            _this.val('');
        }
    }).on('focus','input[name="realPrice"]',function () {//实销价
        var _this = $(this);
        var val = _this.val();
        if(val==0){
            _this.val('');
        }
    }).on('focus','input[name="memberPrice"]',function () {//会员价
        var _this = $(this);
        var val = _this.val();
        if(val==0){
            _this.val('');
        }
    }).on('change','input[name="orPrice"]',function () {
        var _this = $(this);
        var val = _this.val();
        if(val != 0){
            $('input[name="realPrice"]').val(val);
        }
    }).on('click',"#courseImage",function () {//封面上传
        //初始化图片上传窗口
        initUpdateFileWin({
            fileType:'img',//文类类型["img","ico","xls","pdf","zip"]
            callback:'uploadCallback',
            cut:true,//开启剪切
            imgSize:DEFAULT_COURSE_IMG_SIZE,//剪切上传后生成图片的规格（开启剪切才起使用）
            aspectRatio:16/9//剪切区域的高宽比例（开启剪切才起使用）
        });
    }).on('click','#remove-image',function () {//删除封面
        removePageImg();
    }).on('click',"#saveCourse",function () {//保存基本信息
        saveCourse(0);
    }).on('click',"#savePublish",function () {//保存并发布
        saveCourse(1);
    }).on('click',".saveCancel",function () {//取消
        returnUrl(courseTypeKey);
    }).on('click', '#course-info-desc-btn', function () { //展开描述信息表单
        if($(".course-info-desc-box").hasClass('hide')){
            courseInfoDescBox(true);
        }else{
            courseInfoDescBox(false);
        }
    }).on('click','#saveReturn',function () {//描述信息保存，返回
        saveCourseInfo(1);
    }).on('click','#saveNext',function () {//描述信息保存，创建目录排课
        saveCourseInfo(2);
    }).on('click','#secondStep',function () {//描述信息
        courseInfoDescBox(true);
    }).on('click','.goToStep_three',function(){
        var courseId =$('#courseId').val();
        if(courseId!=null&&courseId>0){
            catalogPage(courseTypeKey,courseId);
        }else{
            icModale(0, "请完成前面的步骤");
        }
    }).on('click', '#uploadVideo', function () {//上传视频的时间
        popupWindows();
    }).on('click','#selectVideo',function () {//选择音频、视频
        selectCommonVideo("VIDEO");
    });

    //初始化编辑框
    initSNU({
        id:'context',
        type:1,
        toolsArr:null,
        height:360,
        gs:true,
        video:false
    });

    /**
     * 保存课程数据
     * @param status 状态，0保存，1保存并发布
     */
    function saveCourse(status) {
        var params = $("#save-course-form").serializeJSON();
        delete params['_typeKey'];
        params['status'] = status;
        params = JSON.stringify(params);
        var text = '';
        if(status==1){
            var summary = $("input[name=summary]").val();
            var context = $("#context").val();
            if($.trim(summary)=='' || summary==null){
                text +='课程简介 '
            }
            if($.trim(context)=='' || context==null){
                text +=' 课程详情';
            }
            if(text !=''){
                text +='未填写确认要发布该课程吗？';
            }
        }
        if(text==''){
            _saveCourse(params,status);
        }else{
            icModale(2,text,3,function (index) {
                parent.layer.close(index);
                _saveCourse(params,status);
            });
        }
    }
    function _saveCourse(params,status) {
        $.ajax({
            type:'post',
            url:baseloaction +'/admin/course/cou/saveCourse',
            data:params,
            contentType:'application/json;charset=utf-8',
            success:function (result) {
                if(result.success==false){
                    icModale(0, result.message);
                }else{
                    var courseObject = result.entity;
                    if(status==0){//保存
                        $('.course-type-key').iCheck('disable');
                        icModale(0,'课程基本信息保存成功');
                        $("#courseId").val(courseObject.id);
                        $("#course-info-id").val(courseObject.id);
                        courseInfoDescBox(true);
                    }else if(status==1){//保存并发布
                        returnUrl(courseTypeKey);
                    }
                }
            },
            error:function (error) {
                icModale(0, '系统错误，保存课程数据失败');
            }
        });
    }

    /**
     * 保存课程详情信息
     * @param type 类型，1保存返回，2保存下一步
     */
    function saveCourseInfo(type) {
        var params = $('#course-info-form').serializeJSON();
        params = JSON.stringify(params);
        var courseId = $("#course-info-id").val();
        $.ajax({
            url:baseloaction +'/admin/course/cou/saveCourseInfo',
            type:'post',
            data:params,
            contentType:'application/json;charset=utf-8',
            success:function (result) {
                if(result.success==true){
                    if(type==1){//保存返回
                        returnUrl(courseTypeKey);
                    }else if(type==2){//保存下一步
                        catalogPage(courseTypeKey,courseId);
                    }
                }else{
                    icModale(0, result.message);
                    var key = result.entity;
                    if(key=='NOT_COURSE'){
                        $("html,body").animate({scrollTop:$("#course-animate").offset().top},1000);
                    }
                }
            },
            error:function (error) {
                icModale(0, '系统错误，描述信息保存失败');
            }
        });
    }

    /**
     * 页面跳转路径
     * @param _courseTypeKey
     */
    function returnUrl(_courseTypeKey) {
        if(_courseTypeKey=='PACKAGE'){
            window.location.href = baseloaction +'/admin/course/package/toPackageCourseList';
        }else if(_courseTypeKey=='LIVE'){
            window.location.href = baseloaction +'/admin/course/live/liveList';
        }else if(_courseTypeKey=='SMALL'){
            window.location.href = baseloaction +'/admin/course/small/smallCourseList';
        }else{
            window.location.href = baseloaction +'/admin/course/cou/courseList';
        }
    }

    /**
     * 跳转目录 、套餐下设置课程
     * @param _courseTypeKey
     * @param courseId
     */
    function catalogPage(_courseTypeKey,courseId) {
        if(_courseTypeKey=='PACKAGE'){
            window.location.href = baseloaction +'/admin/course/package/initPackageCoursePage?packageId='+courseId;
        }else if(_courseTypeKey =='LIVE'){
            window.location.href = baseloaction +'/admin/course/catalog/initLiveCatalog?courseId='+courseId;
        }else{
            window.location.href = baseloaction +'/admin/course/catalog/initCourseCatalog?courseId='+courseId;
        }
    }

    /**
     * 显示描述区
     * @param showStatus 状态，true显示，false隐藏
     */
    function courseInfoDescBox(showStatus) {
        if(showStatus){
            $(".course-info-desc-box").removeClass('hide');
            $("#course-info-desc-btn").html('收起描述信息表单');
            $("html,body").animate({scrollTop:$("#info-animate").offset().top},1000);
        }else{
            $(".course-info-desc-box").addClass('hide');
            $("#course-info-desc-btn").html('展开描述信息表单');
        }
    }
});
/**
 * 选择讲师回调
 * @param data
 */
function selectTeacherCallback(data) {
    if (data.length > 0) {
        $('.custom-select-teacher').html('');
        $(data).map(function () {
            var name = this.teacherName;
            var id = this.id;
            $('.custom-select-teacher').append('<option value="' + id + '" class="hide" selected>' + name + '</option>');
        });
        $('.custom-select-teacher').trigger('chosen:updated');
        initTeacherIds();
    }
}
/**
 * 初始化讲师ID串
 */
function initTeacherIds() {
    var op = $('.custom-select-teacher>option:selected');
    if(!$.isEmptyObject(op) && op.length>0 && op!=null){
        var teacherIds = op.map(function () {
            return this.value;
        }).get().join(",");
        teacherIds = ","+teacherIds+",";
        $("input[name='teacherIds']").val(teacherIds);
    }else{
        $("input[name='teacherIds']").val('');
    }
}

/**
 * 图片上传回调
 * @param result
 */
function uploadCallback(result) {
    if(result!=null){
        $("input[name='imageJson']").val(encodeURIComponent(JSON.stringify(result)));
        $("#material-image").attr("src",result.pcUrlMap.large);
        $("#file-names").text(result.fileName);
        $("#create-time").text(result.createTime);
    }
}

function popupWindows() {
    var type = 1;
    var  message='请选择要上传的视频文件';

    index = parent.layer.open({
        type: 2,
        area: ['500px', '100px'],
        content: baseloaction +'/admin/liveToV/create/initVideoUploadPage?type='+type,
        shadeClose: false,
        shade: [0.3, '#000'],
        title: '<strong>'+message+'</strong>'
    });
    setMethods(callbackClose);
}

var close =null;
function setMethods (to){
    close =to;
};
//回调关闭上传素材资源时的公共弹窗
callbackClose = function (){
    parent.layer.close(index);
};
//96k 资源上传回调
parent.window.addEventListener('message', function (response) {
    if (!$.isEmptyObject(response)) {
        $('input[name="audition"]').val(response.data.msg);
        close();
    }
}, false);

/**
 * 选择回调
 * @param video
 */
function selectVideoCallback(video) {
    $("#audition").val(video.code);
}